// 成就展示系统
class AchievementSystem {
    constructor() {
        this.isOpen = false;
        this.achievementDefinitions = this.createAchievementDefinitions();
    }
    
    createAchievementDefinitions() {
        return {
            // 基础成就
            firstKill: {
                name: '首次击杀',
                description: '击杀你的第一只僵尸！',
                icon: '🎯',
                category: '基础',
                difficulty: 'easy'
            },
            levelComplete: {
                name: '关卡完成',
                description: '完成你的第一个关卡！',
                icon: '🏁',
                category: '基础',
                difficulty: 'easy'
            },
            
            // 武器成就
            weaponMaster: {
                name: '武器大师',
                description: '使用过所有类型的武器！',
                icon: '🔫',
                category: '武器',
                difficulty: 'medium'
            },
            
            // 生存成就
            survivor: {
                name: '生存者',
                description: '到达第5关！',
                icon: '🛡️',
                category: '生存',
                difficulty: 'medium'
            },
            unstoppable: {
                name: '无敌',
                description: '完成所有关卡！',
                icon: '👑',
                category: '生存',
                difficulty: 'legendary'
            },
            
            // 击杀成就
            headHunter: {
                name: '猎头者',
                description: '击杀100只僵尸！',
                icon: '💀',
                category: '击杀',
                difficulty: 'medium'
            },
            berserker: {
                name: '狂战士',
                description: '击杀500只僵尸！',
                icon: '⚔️',
                category: '击杀',
                difficulty: 'hard'
            },
            legend: {
                name: '传奇猎手',
                description: '击杀1000只僵尸！',
                icon: '🌟',
                category: '击杀',
                difficulty: 'legendary'
            },
            
            // 精准成就
            sharpShooter: {
                name: '神枪手',
                description: '命中率达到85%！',
                icon: '🎯',
                category: '精准',
                difficulty: 'hard'
            },
            perfectAccuracy: {
                name: '完美精准',
                description: '命中率达到95%！',
                icon: '💎',
                category: '精准',
                difficulty: 'legendary'
            },
            oneShotOneKill: {
                name: '一枪一个',
                description: '50次爆头击杀！',
                icon: '💥',
                category: '精准',
                difficulty: 'hard'
            },
            
            // 连击成就
            doubleDown: {
                name: '双倍击杀',
                description: '连续击杀10个敌人！',
                icon: '🔥',
                category: '连击',
                difficulty: 'medium'
            },
            tripleKill: {
                name: '三连杀',
                description: '连续击杀20个敌人！',
                icon: '⚡',
                category: '连击',
                difficulty: 'hard'
            },
            megaKill: {
                name: '超级连杀',
                description: '连续击杀50个敌人！',
                icon: '💫',
                category: '连击',
                difficulty: 'legendary'
            },
            rampage: {
                name: '大杀特杀',
                description: '连续击杀100个敌人！',
                icon: '🌪️',
                category: '连击',
                difficulty: 'legendary'
            },
            
            // Boss成就
            bossSlayer: {
                name: 'Boss杀手',
                description: '击败你的第一个Boss！',
                icon: '🗡️',
                category: 'Boss',
                difficulty: 'hard'
            },
            tankBuster: {
                name: '坦克克星',
                description: '击杀50个坦克僵尸！',
                icon: '💣',
                category: 'Boss',
                difficulty: 'hard'
            },
            spitterHunter: {
                name: '喷射猎手',
                description: '击杀30个喷射僵尸！',
                icon: '☣️',
                category: 'Boss',
                difficulty: 'medium'
            },
            fastZombieKiller: {
                name: '速度杀手',
                description: '击杀100个快速僵尸！',
                icon: '💨',
                category: 'Boss',
                difficulty: 'hard'
            },
            
            // 完美成就
            perfectLevel: {
                name: '完美关卡',
                description: '完美完成一个关卡（无伤害）！',
                icon: '✨',
                category: '完美',
                difficulty: 'hard'
            },
            invincible: {
                name: '无敌战士',
                description: '完美完成5个关卡！',
                icon: '🛡️',
                category: '完美',
                difficulty: 'legendary'
            },
            
            // 技巧成就
            noReload: {
                name: '不装弹大师',
                description: '在不装弹的情况下完成关卡！',
                icon: '🔫',
                category: '技巧',
                difficulty: 'hard'
            },
            speedDemon: {
                name: '速度恶魔',
                description: '快速完成关卡！',
                icon: '⚡',
                category: '技巧',
                difficulty: 'hard'
            },
            chainKiller: {
                name: '连环杀手',
                description: '20次快速击杀！',
                icon: '⚡',
                category: '技巧',
                difficulty: 'medium'
            },
            
            // 收集成就
            collector: {
                name: '收集家',
                description: '收集50个道具！',
                icon: '📦',
                category: '收集',
                difficulty: 'medium'
            },
            powerUpMaster: {
                name: '道具大师',
                description: '收集200个道具！',
                icon: '🎁',
                category: '收集',
                difficulty: 'hard'
            },
            shieldMaster: {
                name: '护盾大师',
                description: '使用护盾超过5分钟！',
                icon: '🛡️',
                category: '收集',
                difficulty: 'medium'
            },
            
            // 综合成就
            allRounder: {
                name: '全能战士',
                description: '在各个方面都表现出色！',
                icon: '🏆',
                category: '综合',
                difficulty: 'legendary'
            },
            veteran: {
                name: '老兵',
                description: '游戏100次！',
                icon: '🎖️',
                category: '综合',
                difficulty: 'hard'
            }
        };
    }
    
    init() {
        this.createAchievementUI();
        this.setupEventListeners();
    }
    
    createAchievementUI() {
        // 添加成就样式
        this.addAchievementStyles();
    }
    
    addAchievementStyles() {
        const styles = document.createElement('style');
        styles.textContent = `
            .achievement-stats {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
                gap: 15px;
                margin: 20px 0;
                padding: 20px;
                background: rgba(30, 30, 30, 0.8);
                border-radius: 10px;
            }
            
            .stat-item {
                text-align: center;
                padding: 10px;
                background: rgba(50, 50, 50, 0.6);
                border-radius: 5px;
            }
            
            .stat-value {
                font-size: 24px;
                font-weight: bold;
                color: #ff6b6b;
                display: block;
            }
            
            .stat-label {
                font-size: 12px;
                color: #ccc;
                margin-top: 5px;
            }
            
            .achievement-grid {
                display: grid;
                grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
                gap: 15px;
                margin: 20px 0;
                max-height: 50vh;
                overflow-y: auto;
            }
            
            .achievement-item {
                background: linear-gradient(135deg, rgba(40, 40, 40, 0.9), rgba(60, 60, 60, 0.9));
                border: 2px solid #555;
                border-radius: 10px;
                padding: 15px;
                transition: all 0.3s ease;
                position: relative;
                overflow: hidden;
            }
            
            .achievement-item.unlocked {
                border-color: #00ff88;
                background: linear-gradient(135deg, rgba(0, 255, 136, 0.1), rgba(40, 40, 40, 0.9));
            }
            
            .achievement-item.locked {
                opacity: 0.6;
                filter: grayscale(70%);
            }
            
            .achievement-header {
                display: flex;
                align-items: center;
                margin-bottom: 10px;
            }
            
            .achievement-icon {
                font-size: 32px;
                margin-right: 15px;
                filter: drop-shadow(0 2px 4px rgba(0,0,0,0.5));
            }
            
            .achievement-info h3 {
                margin: 0;
                font-size: 16px;
                color: #fff;
                font-weight: bold;
            }
            
            .achievement-category {
                font-size: 10px;
                color: #aaa;
                text-transform: uppercase;
                letter-spacing: 1px;
            }
            
            .achievement-description {
                font-size: 12px;
                color: #ddd;
                line-height: 1.4;
                margin: 10px 0;
            }
            
            .achievement-difficulty {
                position: absolute;
                top: 10px;
                right: 10px;
                padding: 2px 8px;
                border-radius: 12px;
                font-size: 10px;
                font-weight: bold;
                text-transform: uppercase;
            }
            
            .difficulty-easy {
                background: #4CAF50;
                color: white;
            }
            
            .difficulty-medium {
                background: #FF9800;
                color: white;
            }
            
            .difficulty-hard {
                background: #F44336;
                color: white;
            }
            
            .difficulty-legendary {
                background: linear-gradient(45deg, #FFD700, #FFA500);
                color: #000;
                animation: shimmer 2s infinite;
            }
            
            @keyframes shimmer {
                0%, 100% { filter: brightness(1); }
                50% { filter: brightness(1.3); }
            }
            
            .achievement-progress {
                margin-top: 10px;
                height: 4px;
                background: rgba(255, 255, 255, 0.2);
                border-radius: 2px;
                overflow: hidden;
            }
            
            .achievement-progress-bar {
                height: 100%;
                background: linear-gradient(90deg, #ff6b6b, #4ecdc4);
                transition: width 0.3s ease;
            }
            
            .achievement-controls {
                display: flex;
                justify-content: center;
                margin-top: 20px;
                padding: 15px;
                background: rgba(30, 30, 30, 0.8);
                border-radius: 10px;
                position: sticky;
                bottom: 0;
                z-index: 10;
            }
            
            /* 确保成就菜单不会太高 */
            #achievementsMenu {
                max-height: 90vh;
                overflow-y: auto;
            }
            
            .achievement-controls .menu-btn {
                background: linear-gradient(135deg, #ff6b6b, #ee5a52);
                color: white;
                border: none;
                padding: 12px 24px;
                border-radius: 8px;
                font-size: 14px;
                font-weight: bold;
                cursor: pointer;
                transition: all 0.3s ease;
                box-shadow: 0 4px 15px rgba(255, 107, 107, 0.3);
            }
            
            .achievement-controls .menu-btn:hover {
                background: linear-gradient(135deg, #ee5a52, #ff6b6b);
                transform: translateY(-2px);
                box-shadow: 0 6px 20px rgba(255, 107, 107, 0.4);
            }
            
            .category-filter {
                display: flex;
                justify-content: center;
                gap: 6px;
                margin: 15px 0;
                flex-wrap: wrap;
                background: rgba(20, 20, 20, 0.6);
                padding: 8px;
                border-radius: 8px;
            }
            
            .filter-btn {
                padding: 3px 6px;
                background: rgba(70, 70, 70, 0.8);
                border: 1px solid #555;
                border-radius: 12px;
                color: #ccc;
                cursor: pointer;
                transition: all 0.3s ease;
                font-size: 10px;
                min-width: 35px;
                text-align: center;
                white-space: nowrap;
                line-height: 1.2;
            }
            
            .filter-btn:hover,
            .filter-btn.active {
                background: #ff6b6b;
                color: white;
                border-color: #ff6b6b;
            }
            
            .achievement-notification {
                position: fixed;
                top: 20px;
                right: 20px;
                z-index: 10000;
                background: linear-gradient(135deg, rgba(0, 0, 0, 0.95), rgba(30, 30, 30, 0.95));
                border: 2px solid #00ff88;
                border-radius: 10px;
                padding: 15px;
                max-width: 300px;
                box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
                backdrop-filter: blur(10px);
                animation: slideIn 0.5s ease-out;
            }
            
            .achievement-notification-content {
                display: flex;
                align-items: center;
                gap: 15px;
            }
            
            .achievement-notification-icon {
                font-size: 32px;
                filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.5));
            }
            
            .achievement-notification-text h3 {
                margin: 0 0 5px 0;
                font-size: 14px;
                color: #00ff88;
                font-weight: bold;
            }
            
            .achievement-notification-text h4 {
                margin: 0 0 5px 0;
                font-size: 16px;
                color: #fff;
                font-weight: bold;
            }
            
            .achievement-notification-text p {
                margin: 0;
                font-size: 12px;
                color: #ccc;
                line-height: 1.3;
            }
        `;
        document.head.appendChild(styles);
    }
    
    setupEventListeners() {
        // 不再绑定achievementsButton和achievementsBack
        // 这些按钮的事件由main.js统一处理，避免重复绑定
        console.log('成就系统事件监听器设置完成（按钮事件由main.js处理）');
    }
    
    openAchievements() {
        // 使用game实例的hideAllMenus方法保持一致性
        if (window.game && typeof window.game.hideAllMenus === 'function') {
            window.game.hideAllMenus();
            window.game.showMenu('achievementsMenu');
        } else {
            // 回退方案
            document.getElementById('achievementsMenu').classList.remove('hidden');
            document.getElementById('startMenu').classList.add('hidden');
        }
        
        this.updateAchievementDisplay();
        this.isOpen = true;
        console.log('成就系统已打开');
    }
    
    closeAchievements() {
        // 使用game实例的returnToMenu方法保持一致性
        if (window.game && typeof window.game.returnToMenu === 'function') {
            window.game.returnToMenu();
        } else {
            // 回退方案
            const achievementsMenu = document.getElementById('achievementsMenu');
            const startMenu = document.getElementById('startMenu');
            
            if (achievementsMenu) {
                achievementsMenu.classList.add('hidden');
            }
            if (startMenu) {
                startMenu.classList.remove('hidden');
            }
        }
        
        this.isOpen = false;
        console.log('成就系统已关闭，返回主菜单');
    }
    
    updateAchievementDisplay() {
        this.updateStats();
        this.updateAchievementGrid();
    }
    
    // 向后兼容性方法
    updateAchievementUI() {
        this.updateAchievementDisplay();
    }
    
    updateStats() {
        const statsContainer = document.getElementById('achievementStats');
        if (!statsContainer) {
            console.warn('成就统计容器不存在');
            return;
        }
        
        // 直接初始化默认数据，不依赖storageManager
        let data = {
            achievements: {},
            statistics: { accuracy: 0, powerUpsCollected: 0 },
            player: { totalKills: 0, gamesPlayed: 0 },
            progress: { maxLevelReached: 1 }
        };
        
        // 如果存储管理器存在，尝试加载数据
        const storageManager = window.storageManager;
        if (storageManager) {
            try {
                const loadedData = storageManager.loadData();
                if (loadedData) {
                    data = loadedData;
                    // 确保成就数据存在
                    if (!data.achievements) {
                        data.achievements = {};
                    }
                }
            } catch (error) {
                console.warn('存储数据加载失败，使用默认数据:', error);
            }
        }
        
        try {
            
            const unlockedCount = Object.values(data.achievements).filter(a => a).length;
            const totalCount = Object.keys(this.achievementDefinitions).length;
            const completionRate = Math.floor((unlockedCount / totalCount) * 100);
            
            statsContainer.innerHTML = `
                <div class="stat-item">
                    <span class="stat-value">${unlockedCount}/${totalCount}</span>
                    <div class="stat-label">已解锁成就</div>
                </div>
                <div class="stat-item">
                    <span class="stat-value">${completionRate}%</span>
                    <div class="stat-label">完成度</div>
                </div>
                <div class="stat-item">
                    <span class="stat-value">${data.player?.totalKills || 0}</span>
                    <div class="stat-label">总击杀数</div>
                </div>
                <div class="stat-item">
                    <span class="stat-value">${Math.round(parseFloat(data.statistics?.accuracy) || 0)}%</span>
                    <div class="stat-label">命中率</div>
                </div>
                <div class="stat-item">
                    <span class="stat-value">${data.progress?.maxLevelReached || 1}</span>
                    <div class="stat-label">最高关卡</div>
                </div>
                <div class="stat-item">
                    <span class="stat-value">${data.player?.gamesPlayed || 0}</span>
                    <div class="stat-label">游戏次数</div>
                </div>
            `;
        } catch (error) {
            console.error('更新成就统计失败:', error);
            statsContainer.innerHTML = `
                <div style="text-align: center; padding: 20px;">
                    <p>成就数据加载错误，请刷新页面</p>
                </div>
            `;
        }
    }
    
    updateAchievementGrid() {
        const gridContainer = document.getElementById('achievementGrid');
        if (!gridContainer) {
            console.warn('成就网格容器不存在');
            return;
        }
        
        // 直接初始化默认数据，不依赖storageManager
        let data = {
            achievements: {},
            statistics: { accuracy: 0, powerUpsCollected: 0 },
            player: { totalKills: 0, gamesPlayed: 0 },
            progress: { maxLevelReached: 1 }
        };
        
        // 如果存储管理器存在，尝试加载数据
        const storageManager = window.storageManager;
        if (storageManager) {
            try {
                const loadedData = storageManager.loadData();
                if (loadedData) {
                    data = loadedData;
                    // 确保成就数据存在
                    if (!data.achievements) {
                        data.achievements = {};
                    }
                }
            } catch (error) {
                console.warn('存储数据加载失败，使用默认数据:', error);
            }
        }
        
        try {
            const achievements = data.achievements;
        
            // 创建类别过滤器（优化标签长度）
            const categories = [...new Set(Object.values(this.achievementDefinitions).map(a => a.category))];
            const categoryMap = {
                '基础': '基础',
                '武器': '武器', 
                '生存': '生存',
                '击杀': '杀敌',
                '精准': '精准',
                '连击': '连击',
                'Boss': 'Boss',
                '完美': '完美',
                '技巧': '技巧',
                '收集': '收集',
                '综合': '综合'
            };
            const filterHTML = `
                <div class="category-filter">
                    <div class="filter-btn active" data-category="all">全部</div>
                    ${categories.map(cat => `<div class="filter-btn" data-category="${cat}">${categoryMap[cat] || cat}</div>`).join('')}
                </div>
            `;
        
            // 创建成就网格
            const achievementHTML = Object.entries(this.achievementDefinitions).map(([key, definition]) => {
                const isUnlocked = achievements[key] || false;
                const progress = this.calculateProgress(key, data);
                
                return `
                    <div class="achievement-item ${isUnlocked ? 'unlocked' : 'locked'}" data-category="${definition.category}">
                        <div class="achievement-difficulty difficulty-${definition.difficulty}">
                            ${definition.difficulty}
                        </div>
                        <div class="achievement-header">
                            <div class="achievement-icon">${definition.icon}</div>
                            <div class="achievement-info">
                                <h3>${definition.name}</h3>
                                <div class="achievement-category">${definition.category}</div>
                            </div>
                        </div>
                        <div class="achievement-description">${definition.description}</div>
                        ${progress < 100 && !isUnlocked ? 
                            '<div class="achievement-progress">' +
                                '<div class="achievement-progress-bar" style="width: ' + progress + '%"></div>' +
                            '</div>' +
                            '<div style="font-size: 10px; color: #aaa; margin-top: 5px;">进度: ' + progress + '%</div>'
                        : ''}
                        ${isUnlocked ? '<div style="font-size: 12px; color: #00ff88; margin-top: 5px;">✓ 已解锁</div>' : ''}
                    </div>
                `;
            }).join('');
            
            gridContainer.innerHTML = filterHTML + '<div class="achievements-list">' + achievementHTML + '</div>';
            
            // 添加过滤器事件
            const filterButtons = gridContainer.querySelectorAll('.filter-btn');
            filterButtons.forEach(btn => {
                btn.addEventListener('click', () => {
                    filterButtons.forEach(b => b.classList.remove('active'));
                    btn.classList.add('active');
                    
                    const category = btn.dataset.category;
                    const achievements = gridContainer.querySelectorAll('.achievement-item');
                    
                    achievements.forEach(achievement => {
                        if (category === 'all' || achievement.dataset.category === category) {
                            achievement.style.display = 'block';
                        } else {
                            achievement.style.display = 'none';
                        }
                    });
                });
            });
        } catch (error) {
            console.error('更新成就网格失败:', error);
            gridContainer.innerHTML = `
                <div style="text-align: center; padding: 20px;">
                    <p>成就列表加载错误，请刷新页面</p>
                </div>
            `;
        }
    }
    
    calculateProgress(achievementKey, data) {
        const stats = data.statistics;
        const player = data.player;
        const progress = data.progress;
        
        switch (achievementKey) {
            case 'headHunter':
                return Math.min(100, ((player.totalKills || 0) / 100) * 100);
            case 'berserker':
                return Math.min(100, ((player.totalKills || 0) / 500) * 100);
            case 'legend':
                return Math.min(100, ((player.totalKills || 0) / 1000) * 100);
            case 'sharpShooter':
                return Math.min(100, (parseFloat(stats.accuracy) / 85) * 100);
            case 'perfectAccuracy':
                return Math.min(100, (parseFloat(stats.accuracy) / 95) * 100);
            case 'survivor':
                return Math.min(100, ((progress.maxLevelReached || 1) / 5) * 100);
            case 'collector':
                return Math.min(100, ((stats.powerUpsCollected || 0) / 50) * 100);
            case 'powerUpMaster':
                return Math.min(100, ((stats.powerUpsCollected || 0) / 200) * 100);
            case 'veteran':
                return Math.min(100, ((player.gamesPlayed || 0) / 100) * 100);
            case 'tankBuster':
                return Math.min(100, ((stats.zombiesKilledByType?.tank || 0) / 50) * 100);
            case 'spitterHunter':
                return Math.min(100, ((stats.zombiesKilledByType?.spitter || 0) / 30) * 100);
            case 'fastZombieKiller':
                return Math.min(100, ((stats.zombiesKilledByType?.fast || 0) / 100) * 100);
            case 'doubleDown':
                return Math.min(100, ((stats.maxKillStreak || 0) / 10) * 100);
            case 'tripleKill':
                return Math.min(100, ((stats.maxKillStreak || 0) / 20) * 100);
            case 'megaKill':
                return Math.min(100, ((stats.maxKillStreak || 0) / 50) * 100);
            case 'rampage':
                return Math.min(100, ((stats.maxKillStreak || 0) / 100) * 100);
            case 'shieldMaster':
                return Math.min(100, ((stats.shieldTimeUsed || 0) / 300000) * 100); // 5 minutes
            case 'oneShotOneKill':
                return Math.min(100, ((stats.headshotKills || 0) / 50) * 100);
            case 'chainKiller':
                return Math.min(100, ((stats.rapidKills || 0) / 20) * 100);
            case 'invincible':
                return Math.min(100, ((stats.perfectLevels || 0) / 5) * 100);
            default:
                return 0;
        }
    }
    
    checkAchievements() {
        if (!window.storageManager) {
            console.warn('存储管理器未初始化，无法检查成就');
            return;
        }
        
        try {
            const data = window.storageManager.loadData();
            if (!data || !data.achievements) {
                console.warn('成就数据不存在，跳过检查');
                return;
            }
            
            const achievements = data.achievements;
            const stats = data.statistics || {};
            const player = data.player || {};
            const progress = data.progress || {};
        
        // 检查各种成就条件
        const achievementChecks = {
            firstKill: (player.totalKills || 0) >= 1,
            levelComplete: (progress.maxLevelReached || 1) >= 2,
            weaponMaster: stats.weaponsUsed && Object.keys(stats.weaponsUsed).length >= 4,
            survivor: (progress.maxLevelReached || 1) >= 5,
            unstoppable: (progress.maxLevelReached || 1) >= 10,
            headHunter: (player.totalKills || 0) >= 100,
            berserker: (player.totalKills || 0) >= 500,
            legend: (player.totalKills || 0) >= 1000,
            sharpShooter: parseFloat(stats.accuracy) >= 85,
            perfectAccuracy: parseFloat(stats.accuracy) >= 95,
            oneShotOneKill: (stats.headshotKills || 0) >= 50,
            doubleDown: (stats.maxKillStreak || 0) >= 10,
            tripleKill: (stats.maxKillStreak || 0) >= 20,
            megaKill: (stats.maxKillStreak || 0) >= 50,
            rampage: (stats.maxKillStreak || 0) >= 100,
            bossSlayer: (stats.bossKilled || 0) >= 1,
            tankBuster: (stats.zombiesKilledByType?.tank || 0) >= 50,
            spitterHunter: (stats.zombiesKilledByType?.spitter || 0) >= 30,
            fastZombieKiller: (stats.zombiesKilledByType?.fast || 0) >= 100,
            perfectLevel: (stats.perfectLevels || 0) >= 1,
            invincible: (stats.perfectLevels || 0) >= 5,
            collector: (stats.powerUpsCollected || 0) >= 50,
            powerUpMaster: (stats.powerUpsCollected || 0) >= 200,
            shieldMaster: (stats.shieldTimeUsed || 0) >= 300000,
            chainKiller: (stats.rapidKills || 0) >= 20,
            veteran: (player.gamesPlayed || 0) >= 100,
            allRounder: this.checkAllRounder(data)
        };
        
            // 检查每个成就是否已解锁
            for (const [key, condition] of Object.entries(achievementChecks)) {
                if (condition && !achievements[key]) {
                    this.unlockAchievement(key);
                }
            }
        } catch (error) {
            console.error('检查成就时出错:', error);
        }
    }
    
    checkAllRounder(data) {
        const stats = data.statistics;
        const player = data.player;
        const progress = data.progress;
        
        return (player.totalKills || 0) >= 500 &&
               parseFloat(stats.accuracy) >= 80 &&
               (progress.maxLevelReached || 1) >= 8 &&
               (stats.powerUpsCollected || 0) >= 100 &&
               (stats.maxKillStreak || 0) >= 25;
    }
    
    unlockAchievement(achievementKey) {
        if (!window.storageManager) return;
        
        const data = window.storageManager.loadData();
        if (data.achievements[achievementKey]) return; // 已解锁
        
        // 解锁成就
        data.achievements[achievementKey] = true;
        window.storageManager.saveData(data);
        
        // 显示成就通知
        this.showAchievementNotification(achievementKey);
        
        console.log(`成就解锁: ${achievementKey}`);
    }
    
    showAchievementNotification(achievementKey) {
        const definition = this.achievementDefinitions[achievementKey];
        if (!definition) return;
        
        // 创建通知元素
        const notification = document.createElement('div');
        notification.className = 'achievement-notification';
        notification.innerHTML = `
            <div class="achievement-notification-content">
                <div class="achievement-notification-icon">${definition.icon}</div>
                <div class="achievement-notification-text">
                    <h3>成就解锁！</h3>
                    <h4>${definition.name}</h4>
                    <p>${definition.description}</p>
                </div>
            </div>
        `;
        
        // 添加到页面
        document.body.appendChild(notification);
        
        // 动画效果
        setTimeout(() => {
            notification.style.animation = 'slideIn 0.5s ease-out';
        }, 100);
        
        // 自动移除
        setTimeout(() => {
            notification.style.animation = 'slideOut 0.5s ease-in';
            setTimeout(() => {
                if (notification.parentNode) {
                    document.body.removeChild(notification);
                }
            }, 500);
        }, 4000);
    }
}

// 成就系统类定义完成
console.log('AchievementSystem类已定义:', typeof AchievementSystem);
if (window.debugLog) {
    window.debugLog('AchievementSystem类定义完成');
}